import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/artifacts/clickable_avatar_widget.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/artifacts/report_vault_dialog.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/lore/chronicle/whisper_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 单聊页面
class SingleChatRealms extends StatefulWidget {
  const SingleChatRealms({super.key});

  @override
  State<SingleChatRealms> createState() => _SingleChatRealmsState();
}

class _SingleChatRealmsState extends State<SingleChatRealms> {
  final TextEditingController _messageInputController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final FocusNode _inputFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 进入页面时标记所有未读消息为已读
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _markMessagesAsRead();
    });
  }

  @override
  void dispose() {
    _messageInputController.dispose();
    _scrollController.dispose();
    _inputFocusNode.dispose();
    super.dispose();
  }

  /// 标记消息为已读
  void _markMessagesAsRead() {
    final otherUserId = Get.parameters['otherUserId'] ?? '';
    final userChronicle = Get.find<UserChronicle>();
    final whisperChronicle = Get.find<WhisperChronicle>();
    final currentUser = userChronicle.currentUser;

    if (currentUser != null && otherUserId.isNotEmpty) {
      whisperChronicle.markConversationAsRead(currentUser.id, otherUserId);
    }
  }

  @override
  Widget build(BuildContext context) {
    final otherUserId = Get.parameters['otherUserId'] ?? '';
    final userChronicle = Get.find<UserChronicle>();
    final whisperChronicle = Get.find<WhisperChronicle>();

    final currentUser = userChronicle.currentUser;
    final otherUser = userChronicle.queryUserById(otherUserId);

    if (currentUser == null || otherUser == null) {
      return Scaffold(
        backgroundColor: RazeConstants.background,
        body: Center(
          child:
              Text('User not found')
                  .applyTypeSize(16.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans(),
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Column(
          children: [
            // 顶部导航栏
            _constructTopNavigationBar(otherUser, userChronicle),

            // 消息列表区域（白色背景容器）
            Expanded(
              child: Container(
                margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: RazeConstants.white,
                  borderRadius: BorderRadius.circular(10.r),
                  border: Border.all(color: RazeConstants.black, width: 2.w),
                ),
                child: Obx(() {
                  final messages = whisperChronicle.fetchConversation(
                    currentUser.id,
                    otherUserId,
                  );

                  if (messages.isEmpty) {
                    return Center(
                      child:
                          Text('No messages yet')
                              .applyTypeSize(14.sp)
                              .applyTypeColor(
                                RazeConstants.black.withOpacity(0.6),
                              )
                              .applyNotoSans(),
                    );
                  }

                  // 滚动到底部
                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    if (_scrollController.hasClients) {
                      _scrollController.animateTo(
                        _scrollController.position.maxScrollExtent,
                        duration: Duration(milliseconds: 300),
                        curve: Curves.easeOut,
                      );
                    }
                  });

                  return ListView.builder(
                    controller: _scrollController,
                    padding: EdgeInsets.zero,
                    itemCount: messages.length,
                    itemBuilder: (context, index) {
                      final message = messages[index];
                      final isCurrentUser = message.senderId == currentUser.id;
                      return _renderMessageBubble(
                        message: message,
                        isCurrentUser: isCurrentUser,
                        otherUser: otherUser,
                        currentUser: currentUser,
                      );
                    },
                  );
                }),
              ).withRightBottomShadow(thickness: 1),
            ),

            // 底部输入栏
            _composeBottomInputBar(
              currentUser.id,
              otherUserId,
              whisperChronicle,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _constructTopNavigationBar(
    dynamic otherUser,
    UserChronicle userChronicle,
  ) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: SafeArea(
        bottom: false,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 返回按钮
            Container(
                  width: 30.w,
                  height: 30.w,
                  decoration: BoxDecoration(
                    color: RazeConstants.background,
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: RazeConstants.black,
                      width: 1.5.w,
                    ),
                  ),
                  child: Icon(
                    Icons.chevron_left_rounded,
                    size: 24.sp,
                    color: RazeConstants.black,
                  ),
                )
                .withRightBottomShadow(thickness: 1)
                .withTouchResonance(onTap: () => Get.back()),

            Expanded(
              child: Column(
                children: [
                  // 用户头像
                  ClickableAvatarWidget(
                    userId: otherUser.id,
                    avatarPath: otherUser.avatar,
                    width: 30.w,
                    height: 30.w,
                  ),
                  // 用户名
                  Text(otherUser.username)
                      .applyTypeSize(14.sp)
                      .applyTypeColor(RazeConstants.black)
                      .applyBagelFatOne(weight: FontWeight.w500),
                ],
              ),
            ),

            // 举报按钮
            Container(
                  width: 30.w,
                  height: 30.w,
                  decoration: BoxDecoration(
                    color: RazeConstants.background,
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: RazeConstants.black,
                      width: 1.5.w,
                    ),
                  ),
                  padding: EdgeInsets.all(4.w),
                  child: Image.asset(
                    'assets/images/report2.png',
                    width: 20.w,
                    height: 20.w,
                  ),
                )
                .withRightBottomShadow(thickness: 1)
                .withTouchResonance(
                  onTap: () => _initiateReportFlow(otherUser.id),
                ),
          ],
        ),
      ),
    );
  }

  /// 渲染消息气泡
  Widget _renderMessageBubble({
    required dynamic message,
    required bool isCurrentUser,
    required dynamic otherUser,
    required dynamic currentUser,
  }) {
    final user = isCurrentUser ? currentUser : otherUser;

    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Column(
        crossAxisAlignment:
            isCurrentUser ? CrossAxisAlignment.end : CrossAxisAlignment.start,
        children: [
          // 消息气泡
          Container(
            constraints: BoxConstraints(maxWidth: 280.w),
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
            decoration: BoxDecoration(
              color: RazeConstants.yellow,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(14.r),
                topRight: Radius.circular(14.r),
                bottomLeft: Radius.circular(isCurrentUser ? 14.r : 0.r),
                bottomRight: Radius.circular(isCurrentUser ? 0.r : 14.r),
              ),
              border: Border.all(color: RazeConstants.black, width: 1.w),
            ),
            child:
                message.messageType == 'call_failed'
                    ? Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.phone_missed,
                          size: 16.sp,
                          color: RazeConstants.black.withOpacity(0.7),
                        ),
                        6.w.boxWidth,
                        Text(
                          'Missed call',
                          style: TextStyle(
                            fontSize: 13.sp,
                            color: RazeConstants.black.withOpacity(0.7),
                            fontFamily: 'NotoSans',
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                      ],
                    )
                    : Text(message.content)
                        .applyTypeSize(14.sp)
                        .applyTypeColor(RazeConstants.black)
                        .applyNotoSans(),
          ),
          6.h.boxHeight,

          // 用户头像和用户名（在消息气泡下方）
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 头像
              ClickableAvatarWidget(
                userId: user.id,
                avatarPath: user.avatar,
                width: 24.w,
                height: 24.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                ),
              ),
              6.w.boxWidth,
              // 用户名
              Text(user.username)
                  .applyTypeSize(12.sp)
                  .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                  .applyNotoSans(weight: FontWeight.w500),
            ],
          ),
        ],
      ),
    );
  }

  /// 组合底部输入栏
  Widget _composeBottomInputBar(
    String currentUserId,
    String otherUserId,
    WhisperChronicle whisperChronicle,
  ) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            // 摄像头按钮（视频通话）
            Container(
              width: 44.w,
              height: 44.w,
              decoration: BoxDecoration(color: Colors.transparent),
              child: Image.asset(
                'assets/images/video-call.png',
                width: 24.w,
                height: 24.w,
              ),
            ).withTouchResonance(
              onTap: () {
                // 跳转到视频通话页面
                Get.toNamed(
                  '/video-call',
                  parameters: {'otherUserId': otherUserId},
                );
              },
            ),
            12.w.boxWidth,

            // 输入框容器
            Expanded(
              child: Container(
                padding: EdgeInsets.only(
                  left: 16.w,
                  right: 4.w,
                  top: 4.h,
                  bottom: 4.h,
                ),
                decoration: BoxDecoration(
                  color: RazeConstants.white,
                  borderRadius: BorderRadius.circular(16.r),
                  border: Border.all(color: RazeConstants.black, width: 2.w),
                ),
                child: Row(
                  children: [
                    // 输入框
                    Expanded(
                      child: TextField(
                        controller: _messageInputController,
                        focusNode: _inputFocusNode,
                        decoration: InputDecoration(
                          hintText: 'Input Content',
                          hintStyle: TextStyle(
                            fontSize: 14.sp,
                            color: RazeConstants.black.withOpacity(0.4),
                            fontFamily: 'NotoSans',
                          ),
                          border: InputBorder.none,
                          isDense: true,
                          contentPadding: EdgeInsets.symmetric(vertical: 8.h),
                        ),
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: RazeConstants.black,
                          fontFamily: 'NotoSans',
                        ),
                        maxLines: 1,
                      ),
                    ),
                    8.w.boxWidth,

                    // 发送按钮
                    Container(
                          width: 30.w,
                          height: 30.w,
                          decoration: BoxDecoration(
                            color: RazeConstants.yellow,
                            borderRadius: BorderRadius.circular(6.r),
                            border: Border.all(
                              color: RazeConstants.black,
                              width: 1.5.w,
                            ),
                          ),
                          child: Image.asset(
                            'assets/images/send.png',
                            width: 20.w,
                            height: 20.w,
                          ),
                        )
                        .withRightBottomShadow(thickness: 0.5)
                        .withTouchResonance(
                          onTap:
                              () => _dispatchTextMessage(
                                currentUserId,
                                otherUserId,
                                whisperChronicle,
                              ),
                        ),
                    6.w.boxWidth,
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 发送文本消息
  void _dispatchTextMessage(
    String currentUserId,
    String otherUserId,
    WhisperChronicle whisperChronicle,
  ) {
    final content = _messageInputController.text.trim();
    if (content.isEmpty) {
      return;
    }

    // 发送消息
    whisperChronicle.dispatchMessage(
      senderId: currentUserId,
      receiverId: otherUserId,
      messageType: 'text',
      content: content,
    );

    // 清空输入框
    _messageInputController.clear();
    _inputFocusNode.unfocus();
  }

  /// 发起举报流程
  void _initiateReportFlow(String otherUserId) {
    final userChronicle = Get.find<UserChronicle>();
    final whisperChronicle = Get.find<WhisperChronicle>();
    final currentUser = userChronicle.currentUser;

    if (currentUser == null) return;

    ReportVaultDialog.revealReportVault(
      onReportSubmitted: (_) {
        // 举报成功提示
        NotifierGlimmer.revealInfo('Report submitted successfully.');

        // 删除与该用户的所有对话消息
        whisperChronicle.purgeConversation(currentUser.id, otherUserId);

        // 返回上一页
        Get.back();
      },
    );
  }
}
